﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Model;

namespace TaxiDispatchClient
{
    public partial class SpecialCarForm : DevExpress.XtraEditors.XtraForm
    {
        public SpecialCarForm()
        {
            InitializeComponent();
        }

        private Thread _thread;
        private bool _isLoad;
        private bool _isAdd;


        private void SpecialCarForm_Load(object sender, EventArgs e)
        {
 
            //foreach (string s in MainForm.CompanyList)
            //{
            //    comboBoxEdit_company.Properties.Items.Add(s);
            //}

            _isLoad = true;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void BindControlData()
        {
            DataSet dsCompany = new DataSet();

            if (MainForm.MyUserInfo.CompanyName == Service.PowerConfig.MainCompanyName)
            {
                dsCompany = MainForm.PositionService.CompanyGetList("");
                
            }
            else
            {
                dsCompany = MainForm.PositionService.CompanyGetList(
                    "CompanyName like '"+MainForm.MyUserInfo.CompanyName
                    +"%'");
            }
            if (dsCompany != null && dsCompany.Tables.Count > 0)
            {
                foreach (DataRow row in dsCompany.Tables[0].Rows)
                {
                    string id = row["Id"].ToString();
                    string name = row["CompanyName"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = name;
                    item.Value = id;
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        comboBoxEdit_company.Properties.Items.Add(item);
                        imageCombo_companySel.Properties.Items.Add(item);
                    }));
                }
            }

          
            ImageComboBoxItem itemNull = new ImageComboBoxItem("未设置", null);
            BeginInvoke(new MethodInvoker(() =>
                        imageCombo_serverList.Properties.Items.Add(itemNull)));
            DataSet dsServers = MainForm.PositionService.ServerConfigGetList("");
            if (dsServers != null && dsServers.Tables.Count > 0)
            {
                foreach (DataRow row in dsServers.Tables[0].Rows)
                {
                    string id = row["id"].ToString();
                    string serverName = row["ServerName"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = serverName;
                    item.Value = id;
                    BeginInvoke(new MethodInvoker(() =>
                        imageCombo_serverList.Properties.Items.Add(item)));
                }
            }
 
        }
        private void BindGrid()
        {
            try
            {
                DataSet ds = new DataSet();
                string parameterVaule = textEdit_condition.Text.Trim();
                string parameter = "PhoneNumber";
                switch (radioGroup_SelectType.SelectedIndex)
                {
                    case 0:
                        parameter = "PhoneNumber";
                        break;
                    case 1:
                        parameter = "CarNo";
                        break;
                    case 2:
                        parameter = "Type";
                        if (imageCombo_typeSelect.SelectedIndex>=0)
                        {
                            parameterVaule = imageCombo_typeSelect.Properties.Items[
                            imageCombo_typeSelect.SelectedIndex].Value.ToString();    
                        }                        
                        break;
                    case 3:
                        parameter = "CompanyId";
                        if (imageCombo_companySel.SelectedIndex>=0)
                        {
                            parameterVaule = imageCombo_companySel.Properties.Items[
                            imageCombo_companySel.SelectedIndex].Value.ToString();    
                        }                        
                        break;
                }
                
                StringBuilder strWhere = new StringBuilder();
                if (parameterVaule == "")
                {
                    if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                    {
                        strWhere.Append("  CompanyName='");
                        strWhere.Append(MainForm.MyUserInfo.CompanyName);
                        strWhere.Append("'");
                    }

                }
                else
                {
                    strWhere.Append(parameter);
                    strWhere.Append(" like '%");
                    strWhere.Append(parameterVaule);
                    strWhere.Append("%' ");
                    if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                    {
                        strWhere.Append(" and  CompanyName='");
                        strWhere.Append(MainForm.MyUserInfo.CompanyName);
                        strWhere.Append("'");
                    }
                }
                ds = MainForm.PositionService.SpecialCarGetList(strWhere.ToString());
                if (ds != null && ds.Tables.Count == 1)
                {
                    ClearInputControl();

                    ds.Tables[0].Columns.Add("TypeStr");
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        switch (row["Type"].ToString())
                        {
                            case "4":
                                row["TypeStr"] = "救护车";
                                break;
                            case "5":
                                row["TypeStr"] = "警车";
                                break;
                        }
                    }
                    BeginInvoke(new MethodInvoker(() =>
                    {

                        gridControl1.DataSource = ds.Tables[0];
                        gridView1.GroupPanelText = "出租车列表-共" + ds.Tables[0].Rows.Count + "辆";
                        if (_isLoad)
                        {
                            BindControlData();
                            _isLoad = false;
                        }
                        if (_isAdd)
                        {
                            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                            _isAdd = false;
                        }                      
                        btn_select.Enabled = true;
                    }));
                }
                   
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                //  BeginInvoke(new MethodInvoker(() => btn_select.Enabled = true));               
            }
        }
 

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();


                textEdit_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_carNo.Text = row["CarNo"].ToString();
                textEdit_imei.Text = row["IMEI"].ToString();
                textEdit_driverName.Text = row["DriverName"].ToString();
                textEdit_carType.Text = row["CarType"].ToString();

              
                imgComboBox_type.Text = row["Type"].ToString();
        
                comboBoxEdit_company.Text = row["CompanyId"].ToString();
                 
                imageCombo_serverList.Text = row["ServerId"].ToString();
                 
                btn_modify.Enabled = true;
             
          
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    comboBoxEdit_company.SelectedIndex = 0;
                }
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();


                textEdit_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_carNo.Text = row["CarNo"].ToString();
                textEdit_imei.Text = row["IMEI"].ToString();
                textEdit_driverName.Text = row["DriverName"].ToString();
                textEdit_carType.Text = row["CarType"].ToString();


                imgComboBox_type.Text = row["Type"].ToString();

                comboBoxEdit_company.Text = row["CompanyId"].ToString();

                imageCombo_serverList.Text = row["ServerId"].ToString();

                btn_modify.Enabled = true;


                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    comboBoxEdit_company.SelectedIndex = 0;
                }
            }
        }


        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                label_id.Text = "";
                textEdit_PhoneNumber.Text = "";
                textEdit_imei.Text = "";
                textEdit_driverName.Text = "";
                textEdit_carType.Text = "";
                textEdit_carNo.Text = "";



                
                comboBoxEdit_company.Enabled = true;

                textEdit_PhoneNumber.Enabled = true;
                textEdit_imei.Enabled = true;
                textEdit_driverName.Enabled = true;
                textEdit_carType.Enabled = true;
                textEdit_carNo.Enabled = true;

                imgComboBox_type.Enabled = true;
                imgComboBox_type.SelectedIndex = -1;
                imageCombo_serverList.Enabled = true;
                imageCombo_serverList.SelectedIndex = 0;
                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_add.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                string strPhoneNum = textEdit_PhoneNumber.Text.Trim();
                string strCarNo = textEdit_carNo.Text.Trim();
                string strImei = textEdit_imei.Text.Trim();
                string strDriver = textEdit_driverName.Text.Trim();
                string strCarType = textEdit_carType.Text.Trim();

                int type = int.Parse(imgComboBox_type.Properties.Items[
                    imgComboBox_type.SelectedIndex].Value.ToString());

                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
                    comboBoxEdit_company.SelectedIndex].Value.ToString());

            
                int serverid = int.Parse(
                      imageCombo_serverList.Properties.Items[
                      imageCombo_serverList.SelectedIndex].Value.ToString());
                try
                {
                    SpecialCarInfo car = new SpecialCarInfo
                    {                        
                        PhoneNumber = strPhoneNum,
                        CarNo = strCarNo,
                        Imei = strImei,
                        DriverName = strDriver,                      
                        CarType = strCarType,
                        Type = type, 
                        ServerId = serverid, 
                        CompanyId = companyId
                    };
                    if (MainForm.PositionService.SpecialCarAdd(car))
                    {
                        XtraMessageBox.Show("添加成功");
                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_modify.Visible = true;
                        btn_cancel.Visible = false;


                        textEdit_PhoneNumber.Enabled = false;
                        textEdit_imei.Enabled = false;
                        textEdit_driverName.Enabled = false;
                        textEdit_carNo.Enabled = false;
                        textEdit_carType.Enabled = false;

                        imgComboBox_type.Enabled = false;
                        imageCombo_serverList.Enabled = false;                                         
                        comboBoxEdit_company.Enabled = false;

                        btn_add.Enabled = false;

                        btn_add.Tag = "新增";
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        _isAdd = true;
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }


                //taxi.TaxiType=
            }

        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (label_id.Text == string.Empty)
            {
                XtraMessageBox.Show("请选择要修改的出租车！");
                return;
            }
            if (btn_modify.Tag.ToString() == "修改")
            {
                textEdit_carNo.Enabled = true;
                textEdit_carType.Enabled = true;
                
                comboBoxEdit_company.Enabled = true;

                textEdit_PhoneNumber.Enabled = true;
                textEdit_imei.Enabled = true;
                textEdit_driverName.Enabled = true;
                textEdit_carNo.Enabled = true;
                textEdit_carType.Enabled = true;

                imgComboBox_type.Enabled = true;
                imageCombo_serverList.Enabled = true;
               

                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_add.Visible = false;
                btn_modify.Tag = "保存";
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                int id = int.Parse(label_id.Text);
                string strPhoneNum = textEdit_PhoneNumber.Text.Trim();
                string strCarNo = textEdit_carNo.Text.Trim();
                string strImei = textEdit_imei.Text.Trim();
                string strDriver = textEdit_driverName.Text.Trim();
                string strCarType = textEdit_carType.Text.Trim();

                int type = int.Parse(imgComboBox_type.Properties.Items[
                    imgComboBox_type.SelectedIndex].Value.ToString());

                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
                    comboBoxEdit_company.SelectedIndex].Value.ToString());


                int serverid = int.Parse(
                      imageCombo_serverList.Properties.Items[
                      imageCombo_serverList.SelectedIndex].Value.ToString());

                SpecialCarInfo car = new SpecialCarInfo
                {
                    Id = id,
                    PhoneNumber = strPhoneNum,
                    CarNo = strCarNo,
                    Imei = strImei,
                    DriverName = strDriver,
                    CarType = strCarType,
                    Type = type,
                    ServerId = serverid,
                    CompanyId = companyId
                };
                try
                {
                    if (MainForm.PositionService.SpecialCarUpdate(car))
                    {
                        XtraMessageBox.Show("修改成功！");

                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_add.Visible = true;
                        btn_modify.Location = btn_cancel.Location;
                        btn_cancel.Visible = false;
                        btn_modify.Tag = "修改";
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;


                        textEdit_PhoneNumber.Enabled = false;
                        textEdit_imei.Enabled = false;
                        textEdit_driverName.Enabled = false;
                        textEdit_carNo.Enabled = false;
                        textEdit_carType.Enabled = false;

                        imgComboBox_type.Enabled = false;
                        imageCombo_serverList.Enabled = false;
                        comboBoxEdit_company.Enabled = false;


                        btn_add.Enabled = false;

                        //BindGrid();
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的车辆！");
                return;
            }
            id = row["id"].ToString();
            string phoneNum = row["PhoneNumber"].ToString();
            if (XtraMessageBox.Show("确认删除手机号为【" + phoneNum 
                + "】的记录吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.SpecialCarDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }

            }
        }

        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            gridView1.GroupPanelText = "数据加载中...";
            btn_select.Enabled = false;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void simpleButton_cancle_Click(object sender, EventArgs e)
        {
            gridView1_RowClick(null, null);
            gridControl1.Enabled = true;
            btn_select.Enabled = true;
            btn_delete.Visible = true;
            btn_cancel.Visible = false;
            btn_add.Visible = true;
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_modify.Visible = true;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Location = btn_cancel.Location;
            
             
            textEdit_PhoneNumber.Enabled = false;
            textEdit_imei.Enabled = false;
            textEdit_driverName.Enabled = false;
            textEdit_carNo.Enabled = false;
            textEdit_carType.Enabled = false;

            imgComboBox_type.Enabled = false;
            imageCombo_serverList.Enabled = false;
            comboBoxEdit_company.Enabled = false;
             
        }

        public void ClearInputControl()
        {
            BeginInvoke(new MethodInvoker(() =>
                {
                    label_id.Text = "";
                    textEdit_PhoneNumber.Text = "";
                    textEdit_imei.Text = "";
                    textEdit_driverName.Text = "";
                    textEdit_carType.Text = "";
                    textEdit_carNo.Text = "";
                }));            
        }
         
        private bool CheckInput()
        {

            string strPhoneNum = textEdit_PhoneNumber.Text.Trim();
            string strCarNo = textEdit_carNo.Text.Trim();
            string strImei = textEdit_imei.Text.Trim();
            string strDriver = textEdit_driverName.Text.Trim();
            string strCarType = textEdit_carType.Text.Trim();
 
            if (imgComboBox_type.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择该车辆的类型！");
                imgComboBox_type.Focus();
                return false;
            }
             
            if (strPhoneNum == string.Empty)
            {
                XtraMessageBox.Show("出租车手机号码不能为空");
                textEdit_carNo.Focus();
                return false;
            }
            if (strImei.Length > 20)
            {
                XtraMessageBox.Show("IMEI号码输入长度过大！");
                textEdit_imei.Focus();
                return false;
            }
            if (Encoding.GetEncoding("GBK").GetBytes(strDriver).Length > 10)
            {
                XtraMessageBox.Show("司机姓名长度太长！");
                textEdit_driverName.Focus();
                return false;
            }
          
            if (Encoding.GetEncoding("GBK").GetBytes(strCarNo).Length > 8)
            {
                XtraMessageBox.Show("车辆牌照号码输入长度太长");
                textEdit_carNo.Focus();
                return false;
            }             
            if (Encoding.GetEncoding("GBK").GetBytes(strCarType).Length > 12)
            {
                XtraMessageBox.Show("出租车车型输入长度太长（请输入小于6个汉字）");
                textEdit_carType.Focus();
                return false;
            }

 
            if (comboBoxEdit_company.SelectedIndex < 0
                || comboBoxEdit_company.Text == "")
            {
                XtraMessageBox.Show("请选择出租车所属公司");
                comboBoxEdit_company.Focus();
                return false;
            }
            if (imageCombo_serverList.SelectedIndex == 0)
            {
                XtraMessageBox.Show("请选择该出租车所使用的服务器！");
                imageCombo_serverList.Focus();
                return false;
            }
            return true;
        }

        #region  窗体控件操作、效果
        Point _mouseOff;
        bool _leftFlag;
        private void Taxi_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Taxi_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Taxi_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }
        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion

        private void btn_exportToExcel_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "车辆列表";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void From_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }

        

        private void textEdit_condition_KeyPress(object sender, KeyPressEventArgs e)
        {

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                simpleButton_Select_Click(null, null);
            }

        }

        private void radioGroup_SelectType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioGroup_SelectType.SelectedIndex==2)
            {
                imageCombo_typeSelect.Location = textEdit_condition.Location;
                imageCombo_typeSelect.Visible = true;
                textEdit_condition.Visible = false;
                imageCombo_companySel.Visible = false;
            }
            else if (radioGroup_SelectType.SelectedIndex == 3)
            {
                imageCombo_companySel.Location = textEdit_condition.Location;
                imageCombo_companySel.Visible = true;
                imageCombo_typeSelect.Visible = false;
                textEdit_condition.Visible = false;
            }
            else
            {
                textEdit_condition.Visible = true;
                imageCombo_companySel.Visible = false;
                imageCombo_typeSelect.Visible = false;                
            }
        }

      
    }
}